package top.kaoshanji.ch06;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 代码清单 ch06-01：Instant和Duration示例(6.1节、对两个算法计时)
 * author kaoshanji
 * ^_^
 * create time 2024/12/9 11:20
 */
public class Timeline {

    private static final Logger logger = LogManager.getLogger(Timeline.class);

    public static void main(String[] args) {
        logger.info("...代码清单 ch06-01：Instant和Duration示例(6.1节、对两个算法计时)...");

        Instant start = Instant.now(); // 时间线的当前时刻
        runAlgorithm();
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end); // 两个时刻时间的时长
        long millis = timeElapsed.toMillis(); // 转换为传统的秒
        System.out.printf("%d milliseconds\n", millis);

        Instant start2 = Instant.now();
        runAlgorithm2();
        Instant end2 = Instant.now();
        Duration timeElapsed2 = Duration.between(start2, end2);
        System.out.printf("%d milliseconds\n", timeElapsed2.toMillis());

        // multipliedBy 乘以 10
        // minus 减去
        // isNegative 如果 Duration对象是0或负数，则返回 true
        boolean overTenTimesFaster = timeElapsed.multipliedBy(10).minus(timeElapsed2).isNegative();
        System.out.printf("The first algorithm is %smore than ten times faster", overTenTimesFaster ? "" : "not ");

    }

    public static void runAlgorithm() {
        int size = 10;
        List<Integer> list = new Random().ints().map(i -> i % 100).limit(size)
                .boxed().collect(Collectors.toList());
        Collections.sort(list);
        System.out.println(list);
    }

    public static void runAlgorithm2() {
        int size = 10;
        List<Integer> list = new Random().ints().map(i -> i % 100).limit(size)
                .boxed().collect(Collectors.toList());
        while (!IntStream.range(1, list.size())
                .allMatch(i -> list.get(i - 1).compareTo(list.get(i)) <= 0))
            Collections.shuffle(list);
        System.out.println(list);
    }

}
